package controller

import (
	"fmt"
	"github.com/jesusslim/slimgo"
	"github.com/jesusslim/slimmysql"
	"multisql/model"
)

type IndexController struct {
	slimgo.Controller
}

func (this *IndexController) Index() {

}

func (this *IndexController) Exec() {
	theSql := this.Context.Input.GetParam("sql")
	dbs := model.DBS
	res := []map[string]string{}
	for _, db := range dbs {
		s, _ := slimmysql.NewSqlInstance(db)
		result, err := s.Exec(theSql)
		if err != nil {
			tmp := map[string]string{
				"db":    db,
				"error": err.Error(),
			}
			res = append(res, tmp)
		} else {
			num, _ := result.RowsAffected()
			tmp := map[string]string{
				"db":    db,
				"error": fmt.Sprintf("%d", num),
			}
			res = append(res, tmp)
		}
	}
	this.ServeJson(res)
}

func (this *IndexController) Query() {
	theSql := this.Context.Input.GetParam("sql")
	dbs := model.DBS
	res := []map[string]interface{}{}
	for _, db := range dbs {
		s, _ := slimmysql.NewSqlInstance(db)
		result, err := s.Query(theSql)
		if err != nil {
			tmp := map[string]interface{}{
				"db":    db,
				"error": err.Error(),
			}
			res = append(res, tmp)
		} else {
			defer result.Close()
			rows := result
			columns, _ := rows.Columns()
			scanArgs := make([]interface{}, len(columns))
			values := make([]interface{}, len(columns))
			for j := range values {
				scanArgs[j] = &values[j]
			}
			var records_arr []map[string]string
			for rows.Next() {
				record := make(map[string]string)
				rows.Scan(scanArgs...)
				for i, col := range values {
					if col != nil {
						record[columns[i]] = string(col.([]byte))
					} else {
						record[columns[i]] = ""
					}
				}
				records_arr = append(records_arr, record)
			}
			tmp := map[string]interface{}{
				"db":    db,
				"error": records_arr,
			}
			res = append(res, tmp)
		}
	}
	this.ServeJson(res)
}
